#!/bin/bash

load inquirer

help() {
  echo "Get a daemon service logs"
  echo ""
  echo "Usage:"
  echo "  zdaemon logs [options] [app_name]"
  echo ""
  echo "Options:"
  echo "  -f, --follow  Follow logs"
}

core() {
  if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
    help
    exit 0
  fi

  local service=$1
  local args=${@:2}
  
  if [ -z "$service" ]; then
    local available_services=($(daemon_list))
    inquirer::select "Select an service ?" available_services service
  else
    match() {
      string::match $1 ^$service
    }

    local available_services=($(array::filter match $(daemon_list)))
    local available_count=$(array::length $available_services)
    if [ $available_count -eq 0 ]; then
      log::error "no services found"
    elif [ $available_count -eq 1 ]; then
      service=$(array::first_element $available_services)
    else
      inquirer::select "Select an service ?" available_services service
    fi
  fi

  daemon_logs $service $args
}

run() {
  core $@
}

run $@
